import 'dart:async';
import 'package:flutter/material.dart';
import 'package:lib_uikit/lib_uikit.dart';

/// 垂直滚动跑马灯
class GTVerticalMarquee extends StatefulWidget {
  final List<String> list;

  ///停留时间（默认3秒）
  final Duration? stillTime;

  ///动画时间（默认0.5秒）
  final Duration? animTime;

  final ValueChanged<int>? onPageSelected;

  final double? paddingVertical;

  GTVerticalMarquee({
    super.key,
    required this.list,
    this.stillTime,
    this.animTime,
    this.onPageSelected,
    this.paddingVertical,
  });

  @override
  VerticalMarqueeState createState() => VerticalMarqueeState();
}

class VerticalMarqueeState extends State<GTVerticalMarquee> {
  PageController _pageController = PageController();
  late Timer _timer;
  int _currentPage = 0;
  bool _isJumping = false;

  @override
  void initState() {
    super.initState();
    _startMarquee();
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  void _startMarquee() {
    _timer = Timer.periodic(widget.stillTime ?? const Duration(seconds: 3), (timer) {
      if (_pageController.hasClients && !_isJumping) {
        setState(() {
          _currentPage++;
        });
        _pageController.animateToPage(
          _currentPage,
          duration: widget.animTime ?? const Duration(milliseconds: 500),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 创建新的列表，添加一个重复的第一页内容
    final List<String> extendedList = List.from(widget.list)..add(widget.list[0]);
    return Container(
      height: 20 + (widget.paddingVertical ?? 0) * 2,
      child: PageView.builder(
        controller: _pageController,
        scrollDirection: Axis.vertical,
        itemCount: extendedList.length,
        onPageChanged: (index) {
          if (index == extendedList.length - 1 && !_isJumping) {
            // 到达最后一页时，设置跳转标志，跳转到实际的第一页
            _isJumping = true;
            Future.delayed(widget.animTime ?? const Duration(milliseconds: 500), () {
              _pageController.jumpToPage(0);
              setState(() {
                _currentPage = 0;
              });
              _isJumping = false;
            });
          } else {
            setState(() {
              _currentPage = index;
            });
          }
        },
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              if (widget.onPageSelected != null) {
                widget.onPageSelected!(index % widget.list.length);
              }
            },
            child: _buildPage(extendedList[index]),
          );
        },
      ),
    );
  }

  Widget _buildPage(String text) {
    return  Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(vertical: widget.paddingVertical??0),
          child: Text(
            text,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 12, color: GTColorsV3.text3.color),
          ),
        ),
      ],
    );
  }
}
